const fs = require('fs')
const path = require('path')

async function copyDir(src, dest) {
  try {
    await fs.promises.mkdir(dest, { recursive: true }); // 确保目标目录存在
    const entries = await fs.promises.readdir(src, { withFileTypes: true });

    for (let entry of entries) {
      const srcPath = path.join(src, entry.name);
      const destPath = path.join(dest, entry.name);

      entry.isDirectory() ? await copyDir(srcPath, destPath) : await fs.promises.copyFile(srcPath, destPath);
    }
  } catch (err) {
    console.error('An error occurred while copying the directory:', err);
    // 这里可以添加更多的错误处理逻辑，比如重试或通知用户
  }
}

let copyPromise

const generateUniext = {
	name: 'kux-generate-uniext',
	enforce: 'pre',
	config (config) {
		const targetPath = path.resolve(config.root, './uni_modules/kux-router/vite/src/', 'uni-kuxrouter')
		const sourcePath = path.resolve(config.root, './uni_modules/', 'uni-kuxrouter')
		
		copyPromise = copyDir(targetPath, sourcePath)
	},
	buildEnd() {
		return copyPromise
	}
}

module.exports = generateUniext
